<script setup lang="ts">
import dayjs from "dayjs";
import { ref } from "vue";
// import { debounce } from 'lodash-es';
import {
  ElButton,
  ElCard,
  ElCol,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElMessageBox,
  ElOption,
  ElRow,
  ElSelect,
  ElRadioGroup,
  ElRadio,
} from "element-plus";

// import DateRangePicker from '@/components/common/DateRangePicker.vue';
// import Editor from '@/components/common/Editor.vue';
// import Uploader from '@/components/common/Uploader.vue';
// import { ProInputNumber } from '@/modules/package/form';

import useForm from "@/hooks/useForm";
import isSameOrBefore from "dayjs/plugin/isSameOrBefore"; // ES 2015
import useDelay from "@/hooks/useDelay";
import ApiActivity from "@/api/activity";
import { TActivityApplied, TStall } from "@/global";
import { useAppTabs } from "@/modules/package/appTabs";
import router from "@/router";
import useRequest from "@/hooks/useRequest";
import { useRoute } from "vue-router";
import useEnum from "@/hooks/useEnum";
const { list: typeList } = useEnum("EnumActivityAuditStatus");
const { list: fromList } = useEnum("EnumDepositFrom");
const { list: depositStatusList } = useEnum("EnumActivityDepositStatus");

dayjs.extend(isSameOrBefore);

const { params } = useRoute();
const { closeTab } = useAppTabs();
const standList = ref<TStall[]>([]);

// 验证规则
const rules = {
  // title: { required: true, message: "请输入活动标题" },
  // title_img: { required: true, message: "请设置活动封面图" },
};

// S 默认表单数据
const defaultModelValue: Partial<TActivityApplied> = {
  receipt_percent: 0,
  audit_status: 0,
  deposit_from: 1,
  deposit_status: 0,
  deposit_amount: 0,
  deposit_img: "",
};

const { refForm, model, isFetching, submit, reset, onFetchResponse } = useForm<
  TActivityApplied & {
    tag?: string;
  }
>(ApiActivity[params.id ? "activityApplyModify" : "activityApplyAdd"], {
  defaultModel: { ...defaultModelValue },
  formatModel(data) {
    return {
      // ...data,
      id: data.id,
      receipt_percent: parseFloat("" + data.receipt_percent),
      audit_status: data.audit_status,
      deposit_from: data.deposit_from,
      deposit_status: data.deposit_status,
      deposit_amount: data.deposit_amount * 100,
      deposit_img: data.deposit_img,
      stand_id: data.stand_id,
    };
  },
});

onFetchResponse(() => {
  if (!!params.id) {
    ElMessage.success("活动商家编辑成功！");
    router.go(-1);
    closeTab();
  } else {
    ElMessageBox.confirm("活动添加成功！", {
      type: "success",
      confirmButtonText: "返回列表",
      cancelButtonText: "继续添加",
      closeOnClickModal: false,
      showClose: false,
    })
      .then(() => {
        router.push("/activity/list");
        closeTab();
      })
      .catch(() => {
        // @ts-expect-error
        model.value = { ...defaultModelValue };
      });
  }
});

const {
  isFetching: isFetchingWithStandList,
  run: runStandList,
  data: standListData,
  onFetchResponse: onResponseWithStandList,
} = useRequest(ApiActivity.standList, { immediate: false });

// 获取活动商户详情
const {
  isFetching: isFetchingWithDetail,
  data,
  onFetchResponse: onFetchResponseWithDetail,
} = useRequest(ApiActivity.activityApplyDetail, {
  immediate: !!params.id,
  defaultParams: { id: +params.id },
});

onFetchResponseWithDetail(() => {
  const { detail } = data.value;
  // console.log(detail)
  runStandList({ act_id: detail.act_id, page: 1, size: 20 });
  if (detail.deposit_amount > 0) {
    detail.deposit_amount = detail.deposit_amount / 100;
  }

  // model.value = {
  //     receipt_percent: detail.receipt_percent,
  //     audit_status: detail.audit_status,
  //     deposit_from: detail.deposit_from,
  //     deposit_status: detail.deposit_status,
  //     deposit_amount: detail.deposit_amount / 100,
  //     deposit_img: detail.deposit_img,
  // };
  model.value = {
    ...detail,
  };
});

onResponseWithStandList(() => {
  // console.log(standList.value)
  standList.value = standListData.value.list;
});

/**
 * 上传图片成功
 */
// const handleUploadSus = (url: string) => {
//     fileList.value.push({
//         url,
//         uid: new Date().getTime(),
//     });
// };

/**
 * 删除图片前钩子：二次弹窗确认
 */
// const handleBeforeRemove = () => ElMessageBox.alert("确定删除这张图片？");

/**
 * 移除图片
 */
// const handleRemove = (uploadFile: UploadFile) => {
//     const index = fileList.value.findIndex(e => e.uid == uploadFile.uid);
//     fileList.value.splice(index, 1);
// };

// 提交
const handleSubmit = () => {
  submit().catch((err) => {
    // @ts-expect-error
    const [res] = Object.values(err)[0];
    ElMessage.error(res.message);
  });
};

const [state] = useDelay();

// const isSetCoverMode = ref(false);
// /**设置封面图 */
// const setCoverFromFileList = ({ url }: any) => {
//     model.value.title_img = url;
//     isSetCoverMode.value = false;
// };
</script>

<template>
  <Teleport to="#containerFooter" v-if="state">
    <div class="flex-center py-3" v-loading="isFetchingWithDetail">
      <ElButton type="" size="large" :disabled="isFetching" @click="reset"
        >重置</ElButton
      >
      <ElButton
        type="primary"
        size="large"
        :loading="isFetching"
        @click="handleSubmit()"
        >保存</ElButton
      >
      <!-- <ElButton type="warning" size="large"
                      :loading="isFetching"
                      @click="handleSubmit(0)">保存并发布</ElButton> -->
    </div>
  </Teleport>

  <div
    class="w-full mx-auto"
    v-loading="isFetchingWithDetail"
    element-loading-text="正在加载数据"
  >
    <ElForm
      ref="refForm"
      label-width="7em"
      :rules="rules"
      :model="model"
      :loading="isFetching"
    >
      <ElCard header="基础信息">
        <ElRow :gutter="16">
          <ElCol :span="24">
            <ElFormItem label="主办方抽成" prop="receipt_percent">
              <ElInput
                class="w-[200px]"
                v-model="model.receipt_percent"
                placeholder="请输入主办方抽成"
                maxlength="30"
              >
                <template #append>%</template>
              </ElInput>
            </ElFormItem>
          </ElCol>

          <ElCol :span="24">
            <ElFormItem label="审核状态" class="w-full" prop="audit_status">
              <ElRadioGroup v-model="model.audit_status">
                <ElRadio
                  v-for="item in typeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </ElRadioGroup>
            </ElFormItem>
          </ElCol>

          <ElCol :span="24">
            <ElFormItem label="选择展位" class="w-[400px]" prop="stand_id">
              <ElSelect
                v-model="model.stand_id"
                :loading="isFetchingWithStandList"
              >
                <ElOption
                  v-for="item in standList"
                  :label="item.stand_title"
                  :value="item.id"
                />
              </ElSelect>
            </ElFormItem>
          </ElCol>

          <ElCol :span="24">
            <ElFormItem label="押金来源" class="w-full" prop="deposit_from">
              <ElRadioGroup v-model="model.deposit_from">
                <ElRadio
                  v-for="item in fromList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </ElRadioGroup>
            </ElFormItem>
          </ElCol>

          <ElCol :span="24">
            <ElFormItem label="押金金额" class="w-full" prop="deposit_amount">
              <ElInput
                class="w-[200px]"
                v-model="model.deposit_amount"
                placeholder="请输入押金金额"
                maxlength="30"
              >
                <template #append>元</template>
              </ElInput>
            </ElFormItem>
          </ElCol>

          <ElCol :span="24">
            <ElFormItem label="押金状态" class="w-full" prop="deposit_status">
              <ElRadioGroup v-model="model.deposit_status">
                <ElRadio
                  v-for="item in depositStatusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </ElRadioGroup>
            </ElFormItem>
          </ElCol>
          <!-- <ElCol :span="24">
                        <ElFormItem label="支付凭证" prop="deposit_mg">
                            <ElSpace>
                                <UploaderSingle v-model="model.deposit_img"
                                                :before-remove="handleBeforeRemove"
                                                :on-remove="handleRemove" @success="handleUploadSus" />
                            </ElSpace>
                    
                        </ElFormItem>
                    </ElCol> -->
        </ElRow>
      </ElCard>
    </ElForm>
  </div>
</template>
